﻿
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <atlimage.h>
#include "desktop_capturer.h"

void save_image(const sbeidc_frame* frame, const char * filename) {

	// 位图第一部分，文件信息

	BITMAPFILEHEADER bfh;

	bfh.bfType = 0x4d42; //bm

	bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

	bfh.bfSize = bfh.bfOffBits + frame->size;

	bfh.bfReserved1 = 0; // reserved

	bfh.bfReserved2 = 0; // reserved

	// 位图第二部分，数据信息

	BITMAPINFOHEADER bih;

	bih.biSize = sizeof(BITMAPINFOHEADER);

	bih.biWidth = frame->width;

	bih.biHeight = -(int)frame->height;

	bih.biPlanes = 1;

	bih.biBitCount = 32;

	bih.biCompression = 0;

	bih.biSizeImage = frame->size;

	bih.biXPelsPerMeter = 0;

	bih.biYPelsPerMeter = 0;

	bih.biClrUsed = 0;

	bih.biClrImportant = 0;

	IStream* bmp_memory = NULL;
	//创建png流
	IStream* png_Memory = NULL;
	//申请一块bmp全局内存缓冲区
	HGLOBAL bmpHglobal = GlobalAlloc(GMEM_MOVEABLE, 0);
	//申请一块png全局内存缓冲区
	HGLOBAL png_Hglobal = GlobalAlloc(GMEM_MOVEABLE, 0);
	//将流与内存缓冲区关联
	CreateStreamOnHGlobal(bmpHglobal, TRUE, &bmp_memory);
	//将流与内存缓冲区关联
	CreateStreamOnHGlobal(png_Hglobal, TRUE, &png_Memory);
	//定义流数据
	LARGE_INTEGER zero = { 0 };
	ULARGE_INTEGER len = { 0 };

	//重置流起始位置
	bmp_memory->Seek(zero, STREAM_SEEK_SET, NULL);
	//写入位图文件头
	bmp_memory->Write(&bfh, sizeof(BITMAPFILEHEADER), NULL);
	//写入位图信息头
	bmp_memory->Write(&bih, sizeof(BITMAPINFOHEADER), NULL);
	//写入位图数据
	bmp_memory->Write(frame->data, frame->size, NULL);
	//重新定位到IStream头
	bmp_memory->Seek(zero, STREAM_SEEK_SET, NULL);

	//创建image
	CImage *memoryImage = new CImage();
	//通过流加载image
	memoryImage->Load(bmp_memory);
	/*******************保存bmp为png************************************/
	//保存bmp为png
	memoryImage->Save(png_Memory, Gdiplus::ImageFormatJPEG);
	//获取流数据长度
	png_Memory->Seek(zero, STREAM_SEEK_CUR, &len);

	//转换
	int size2 = unsigned long(len.LowPart);
	ULONG Readtotal = len.LowPart;
	byte *data2 = new byte[size2];
	//获取内存转换png数据
	ULONG uLongRet;
	png_Memory->Seek(zero, STREAM_SEEK_SET, NULL);
	png_Memory->Read(data2, size2, &uLongRet);

	/**手动释放资源 */
	GlobalFree(bmp_memory);
	GlobalFree(png_Memory);

	std::ofstream outFile2;
	outFile2.open(filename, std::ios::out | std::ios::binary);
	outFile2.write((char*)data2, size2);
	outFile2.flush();
	outFile2.close();

}

int count = 0;
char *name = new char[100]();
void video_cb(const sbeidc_frame* video_frame) {
	sprintf_s(name, 100, "image%d.bmp", count++);
	save_image(video_frame, name);
}

int main()
{
	sbeidc_cfg cfg = { 0 };
	cfg.max_frame = 60;
	cfg.pfs = 20;

	void* handle = nullptr;
	sbeidc_create(&handle, &cfg);

	sbeidc_cb cb = { &video_cb };
	sbeidc_start(handle, &cb);


	sbeidc_wait(handle);

	sbeidc_stop(handle);

	sbeidc_release(handle);

    std::cout << "Hello World!\n";
}
